package controllers

import (
	"strings"

	"newAi/new_web/models"
	"fmt"
	"time"

	"strconv"
	"unicode"

	"github.com/tealeg/xlsx"
	"os"
)

type NumberController struct {
	BaseController
}

var numberState = [10]string{"未呼叫", "振铃", "已呼出", "已结束"}

func (self *NumberController) List() {
	self.Data["pageTitle"] = "号码管理"
	self.display()
}
func IsDigits(str string) bool {
	for _, r := range str {
		if unicode.IsDigit(r) == false {
			return false
		}
	}
	return true
}
func (self *NumberController) Import() {
	//self.Data["pageTitle"] = "导入号码"
	//self.display()
	path, err := self.UploadFile("./upload/excel/", "uploadField")
	if err != nil {
		fmt.Println(err)
	}
	numbers := models.AiNumbers{}
	groupmap := models.GroupMap{}
	group_id, _ := self.GetInt64("group_id")
	excelFileName := path
	xlFile, err := xlsx.OpenFile(excelFileName)
	if err != nil {
		fmt.Println("open excel error :", err.Error())
	}
	var ifAddTrue = false
	for _, sheet := range xlFile.Sheets {
		for _, row := range sheet.Rows {
			fmt.Println("===============")
			fmt.Println(row.Cells)
			if len(row.Cells) == 0 {
				continue
			}
			Dest_number := row.Cells[0].String()
			Dest_number = strings.Trim(Dest_number, " ")
			Dest_number = strings.Trim(Dest_number, "-")
			if IsDigits(Dest_number) == false || len(Dest_number) < 4 {
				continue
			}
			number_id, err := numbers.CheckNumber(Dest_number)
			if err != nil || number_id == 0 {
				numbers.Dst_number = Dest_number
				//numbers.Last_call_time = row.Cells[1].String()
				//numbers.Num_state, _ = row.Cells[2].Int()
				if len(row.Cells) <= 1 {
					numbers.Num_own = " "
				} else {
					numbers.Num_own = row.Cells[1].String()
				}
				_, err = models.AiNumbersAdd(&numbers)
				groupmap.Group_id = group_id
				groupmap.Number_id = numbers.Id
				groupmap.Has_called = 0

				var arr = []string{" ", " ", " ", " ", " ", " ", " ", " ",
				 " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "}
				for i := 0; i < len(row.Cells); i++ {
					arr[i] = row.Cells[i].String()
				}
				groupmap.Param1 = arr[2]
				groupmap.Param2 = arr[3]
				groupmap.Param3 = arr[4]
				groupmap.Param4 = arr[5]
				groupmap.Param5 = arr[6]
				groupmap.Param6 = arr[7]
				groupmap.Param7 = arr[8]
				groupmap.Param8 = arr[9]
				groupmap.Param9 = arr[10]
				groupmap.Param10 = arr[11]
				groupmap.Param1_type = arr[12]
				groupmap.Param2_type = arr[13]
				groupmap.Param3_type = arr[14]
				groupmap.Param4_type = arr[15]
				groupmap.Param5_type = arr[16]
				groupmap.Param6_type = arr[17]
				groupmap.Param7_type = arr[18]
				groupmap.Param8_type = arr[19]
				groupmap.Param9_type = arr[20]
				groupmap.Param10_type = arr[21]

				if models.CheckNumberMap(group_id, groupmap.Number_id) {
					_, merr := models.GroupMapAdd(&groupmap)
					numbers.Id++
					groupmap.Id++
					if err != nil {
						println("insert to db error :", err.Error())
					}
					if merr != nil {
						println("insert group map to db error :", err.Error())
					}
					ifAddTrue = true //有值添加成功
				}
			} else {
				groupmap.Group_id = group_id
				groupmap.Number_id = number_id
				groupmap.Has_called = 0

				var arr = []string{" ", " ", " ", " ", " ", " ", " ", " ",
					 " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "}
				for i := 0; i < len(row.Cells); i++ {
					arr[i] = row.Cells[i].String()
				}
				groupmap.Param1 = arr[2]
				groupmap.Param2 = arr[3]
				groupmap.Param3 = arr[4]
				groupmap.Param4 = arr[5]
				groupmap.Param5 = arr[6]
				groupmap.Param6 = arr[7]
				groupmap.Param7 = arr[8]
				groupmap.Param8 = arr[9]
				groupmap.Param9 = arr[10]
				groupmap.Param10 = arr[11]
				groupmap.Param1_type = arr[12]
				groupmap.Param2_type = arr[13]
				groupmap.Param3_type = arr[14]
				groupmap.Param4_type = arr[15]
				groupmap.Param5_type = arr[16]
				groupmap.Param6_type = arr[17]
				groupmap.Param7_type = arr[18]
				groupmap.Param8_type = arr[19]
				groupmap.Param9_type = arr[20]
				groupmap.Param10_type = arr[21]

				if models.CheckNumberMap(group_id, groupmap.Number_id) {
					_, merr := models.GroupMapAdd(&groupmap)
					groupmap.Id++
					if merr != nil {
						println("insert group map to db error :", err.Error())
					}
					ifAddTrue = true //有值添加成功
				}
			}

		}
	}
	if ifAddTrue { //如果有修改的值。就把task state值变成未开始
		err := models.UptateTaskState(group_id)
		if err != nil {
			fmt.Println(err)
			self.ajaxMsg("修改task表失败", MSG_ERR)
		}
	}
	if err == nil {
		self.ajaxMsg("", MSG_OK)
		self.redirect("/number/maplist?group_id=" + strconv.FormatInt(group_id, 10))

	}
	self.ajaxMsg("", MSG_OK)
}
func (self *NumberController) TxtImport() {
	path, err := self.UploadFile("upload/txt/", "uploadField")
	if err != nil {
		fmt.Println(err)
	}
	numbers := models.AiNumbers{}            //号码数据库
	group_id, _ := self.GetInt64("group_id") //号码组 id
	excelFileName := path                    //获取上传文件的路径
	file, err := os.Open(excelFileName)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()
	var ifAddTrue = false

	for {
		var groupmap = models.GroupMap{} //号码关系数据库
		var number string
		_, err := fmt.Fscanln(file, &number)
		// scans until newline
		if err != nil {
			break
		}
		//先查看这个号码 在号码组里面是否存在
		number_id, err := numbers.CheckNumber(number)
		//添加入号码数据库
		groupmap.Number_id = number_id
		if err != nil || number_id == 0 {
			numbers.Dst_number = number
			numbers.Num_own = " "
			_, err = models.AiNumbersAdd(&numbers)
			groupmap.Number_id = numbers.Id
		}
		//添加入号码关系数据库
		groupmap.Group_id = group_id
		groupmap.Has_called = 0
		groupmap.Param1 = " "
		groupmap.Param2 = " "
		groupmap.Param3 = " "
		groupmap.Param4 = " "
		groupmap.Param5 = " "
		groupmap.Param6 = " "
		if models.CheckNumberMap(group_id, groupmap.Number_id) {
			_, _ = models.GroupMapAdd(&groupmap)
		}
		ifAddTrue = true //有值添加成功
	}
	if ifAddTrue { //如果有修改的值。就把task state值变成未开始
		err := models.UptateTaskState(group_id)
		if err != nil {
			fmt.Println(err)
			self.ajaxMsg("修改task表失败", MSG_ERR)
		}
	}
	self.ajaxMsg("成功", 0)
}

func (self *NumberController) GroupList() {
	self.Data["pageTitle"] = "组管理"
	gid, _ := self.GetInt64("group_id")
	self.Data["group_id"] = gid
	self.display()
}

func (self *NumberController) GroupAdd() {
	self.Data["pageTitle"] = "新增组"
	if self.isOrg == true {
		self.SetUserGroup(self.userId)
	} else {
		self.SetAllGroup()
	}
	self.display()
}

func (self *NumberController) MapList() {
	self.Data["pageTitle"] = "号码组管理"
	self.Data["group_id"], _ = self.GetInt("id")
	self.display()
}

func (self *NumberController) MapAdd() {
	self.Data["pageTitle"] = "新增号码组"
	self.display()
}

func (self *NumberController) Edit() {
	self.Data["pageTitle"] = "编辑号码"

	id, _ := self.GetInt("id", 0)
	AiNumbers, _ := models.AiNumbersGetById(id)
	row := make(map[string]interface{})
	row["id"] = AiNumbers.Id
	row["dst_number"] = AiNumbers.Dst_number
	//
	row["num_own"] = AiNumbers.Num_own
	self.Data["number"] = row
	self.display()

}

func (self *NumberController) GroupEdit() {
	self.Data["pageTitle"] = "编辑号码组"
	if self.isOrg == true {
		self.SetUserGroup(self.userId)
	} else {
		self.SetAllGroup()
	}
	id, _ := self.GetInt("id", 0)
	NumberGroup, _ := models.NumberGroupGetById(id)
	row := make(map[string]interface{})
	row["id"] = NumberGroup.Id
	row["group_name"] = NumberGroup.Group_name
	row["own_id"] = NumberGroup.Own_id
	self.Data["numbergroup"] = row
	self.display()

}

func (self *NumberController) MapEdit() {
	self.Data["pageTitle"] = "编辑号码组"

	id, _ := self.GetInt("id", 0)
	NumberGroup, _ := models.NumberGroupGetById(id)
	row := make(map[string]interface{})
	row["id"] = NumberGroup.Id
	row["group_name"] = NumberGroup.Group_name
	row["own_id"] = NumberGroup.Own_id
	self.Data["numbergroup"] = row
	self.display()

}

func (self *NumberController) AjaxSave() {
	AiNumbers_id, _ := self.GetInt("id")
	if AiNumbers_id == 0 {
		AiNumbers := new(models.AiNumbers)
		AiNumbers.Dst_number = strings.TrimSpace(self.GetString("dst_bumber"))
		//AiNumbers.Num_state, _ = self.GetInt("num_state")
		//AiNumbers.Last_call_time = self.GetString("last_call_time")
		AiNumbers.Num_own = self.GetString("num_own")
		// 检查登录名是否已经存在
		_, err := models.AiNumbersGetByName(AiNumbers.Dst_number)

		if err == nil {
			self.ajaxMsg("名称已经存在", MSG_ERR)
		}
		//新增
		if _, err := models.AiNumbersAdd(AiNumbers); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		self.ajaxMsg("", MSG_OK)
	}

	AiNumbers, _ := models.AiNumbersGetById(AiNumbers_id)
	//修改

	AiNumbers.Dst_number = strings.TrimSpace(self.GetString("dst_bumber"))
	//AiNumbers.Num_state, _ = self.GetInt("num_state")
	//AiNumbers.Last_call_time = self.GetString("last_call_time")
	AiNumbers.Num_own = self.GetString("num_own")

	if err := AiNumbers.Update(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("", MSG_OK)
}

func (self *NumberController) GroupAjaxSave() {
	NumberGroup_id, _ := self.GetInt("id")
	if NumberGroup_id == 0 {
		NumberGroup := new(models.NumberGroup)
		NumberGroup.Group_name = strings.TrimSpace(self.GetString("group_name"))
		NumberGroup.Own_id, _ = self.GetInt("own_id")
		NumberGroup.Create_time = time.Now().Format("2006-01-02 15:04:05")
		// 检查登录名是否已经存在
		_, err := models.NumberGroupGetByName(NumberGroup.Group_name,NumberGroup.Own_id)

		if err == nil {
			self.ajaxMsg("名称已经存在", MSG_ERR)
		}
		//新增
		if _, err := models.NumberGroupAdd(NumberGroup); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		self.ajaxMsg("", MSG_OK)
	}

	NumberGroup, _ := models.NumberGroupGetById(NumberGroup_id)
	//修改

	NumberGroup.Group_name = strings.TrimSpace(self.GetString("group_name"))
	NumberGroup.Own_id, _ = self.GetInt("own_id")
	NumberGroup.Create_time = self.FormatTime(NumberGroup.Create_time)
	if err := NumberGroup.Update(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("", MSG_OK)
}

//func (self *NumberController) MapAjaxSave() {
//	NumberGroup_id, _ := self.GetInt("id")
//	if NumberGroup_id == 0 {
//		NumberGroup := new(models.NumberGroup)
//		NumberGroup.Group_name = strings.TrimSpace(self.GetString("group_name"))
//		NumberGroup.Own_id, _ = self.GetInt64("own_id")
//		NumberGroup.Create_time = time.Now().Format("2006-01-02 15:04:05")
//		// 检查登录名是否已经存在
//		_, err := models.NumberGroupGetByName(NumberGroup.Group_name)
//
//		if err == nil {
//			self.ajaxMsg("名称已经存在", MSG_ERR)
//		}
//		//新增
//		if _, err := models.NumberGroupAdd(NumberGroup); err != nil {
//			self.ajaxMsg(err.Error(), MSG_ERR)
//		}
//		self.ajaxMsg("", MSG_OK)
//	}
//
//	NumberGroup, _ := models.NumberGroupGetById(NumberGroup_id)
//	//修改
//
//	NumberGroup.Group_name = strings.TrimSpace(self.GetString("group_name"))
//	NumberGroup.Own_id, _ = self.GetInt64("own_id")
//
//	if err := NumberGroup.Update(); err != nil {
//		self.ajaxMsg(err.Error(), MSG_ERR)
//	}
//	self.ajaxMsg("", MSG_OK)
//}

func (self *NumberController) AjaxDel() {

	AiNumbers_id, _ := self.GetInt("id")
	AiNumbers, _ := models.AiNumbersMapGetById(AiNumbers_id)

	if err := AiNumbers.Delete(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("", MSG_OK)
}

func (self *NumberController) GroupAjaxDel() {

	NumberGroup_id, _ := self.GetInt("id")
	NumberGroup, _ := models.NumberGroupGetById(NumberGroup_id)

	if err := NumberGroup.Delete(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("", MSG_OK)
}

func (self *NumberController) Table() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "num_state", 0)
	result, count := models.AiNumbersGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["dst_number"] = v.Dst_number
		//row["num_state"] = v.Num_state
		//row["last_call_time"] = self.FormatTime(v.Last_call_time)
		row["num_own"] = v.Num_own
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *NumberController) MapTable() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	//获取组id
	Group_id, _ := self.GetInt("group_id")
	//查询条件
	//filters := make([]interface{}, 0)
	//filters = append(filters, "has_called", 0)
	result, count := models.NumberGroupMapGetList(page, self.pageSize, Group_id)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["mid"] = v.Map_id
		row["group_name"] = v.Group_name
		row["dst_number"] = v.Dst_number
		row["num_state"] = numberState[v.Num_state]
		row["last_call_time"] = self.FormatTime(v.Last_call_time)
		row["num_own"] = v.Num_own
		row["param1"] =  v.Param1
		row["param2"] =  v.Param2
		row["param3"] =  v.Param3
		row["param4"] =  v.Param4
		row["param5"] =  v.Param5
		row["param6"] =  v.Param6
		row["param7"] =  v.Param7
		row["param8"] =  v.Param8
		row["param9"] =  v.Param9
		row["param10"] =  v.Param10
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *NumberController) GroupTable() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	//查询条件
	user_group, err := models.UserGroupIdName()
	self.CheckError(err)
	filters := make([]interface{}, 0)
	if self.isOrg == true {
		filters = append(filters, "own_id", self.userId)
	}
	result, count := models.NumberGroupGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["group_name"] = v.Group_name
		for _, b := range user_group {
			if v.Own_id == b.Id {

				row["own_id"] = b.LoginName
			}
		}
		row["create_time"] = self.FormatTime(v.Create_time)
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *NumberController) ResetNumber()  {
	id,_ := self.GetInt64("id")
	err:=models.UptateResetNumberMap(id)
	if err != nil {
		self.ajaxMsg("失败", MSG_ERR)
	}
	self.ajaxMsg("成功", MSG_OK)

}